//
//  ViewController.m
//  panotest
//
//  Created by mac on 2022/10/14.
//

#import "ViewController.h"
#import "pano.h"
#import "TZImagePickerController.h"
#import <Photos/Photos.h>
#import "SVProgressHUD.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, strong) NSMutableArray *selectedLocalPhotos;
@property (nonatomic, strong) NSMutableArray *selectedLocalAssets;
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;

@end

@implementation ViewController
- (NSMutableArray *)dataArray {
    if(_dataArray) return _dataArray;
    _dataArray = [NSMutableArray array];
    [_dataArray addObject:@"预览"];
    [_dataArray addObject:@"合成"];
    [_dataArray addObject:@"补地"];

    return _dataArray;
}
- (UITableView *)tableView {
    if(_tableView) return _tableView;
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 50)];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    return _tableView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(cell == nil) {
        cell  = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:cellID];
    }
    cell.textLabel.text = self.dataArray[indexPath.item];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.item == 0) {
        [self showImage];
    } else if(indexPath.item == 1) {
        [self finshUtil];
    } else if(indexPath.item == 2) {
        [self addBottom];
    }
}

- (void)showImage {
    [self showImageWithFilePath:[[NSBundle mainBundle] pathForResource:@"a" ofType:@"jpg"]];
}

- (void)finshUtil {
    NSMutableArray *_selectedLocalAssets = [NSMutableArray array];
    NSMutableArray *selectedLocalPhotos = [NSMutableArray array];
    
//
//}
//- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:15 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.selectedAssets = self.selectedLocalAssets;
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO; // self.allowCropSwitch.isOn;
    imagePickerVc.needCircleCrop = NO;// self.needCircleCropSwitch.isOn;
    NSInteger left = 30;
    NSInteger widthHeight = self.view.frame.size.width - 2 * left;
    NSInteger top = (self.view.frame.size.height - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.preferredLanguage = @"zh-Hans";
    
    imagePickerVc.hideWhenCanNotSelect = YES;
//    imagePickerVc.allowAddProportion = YES;
    imagePickerVc.addProportion = 2.0;
//    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//        NSLog(@"%@", photos);
//    }];
//
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedLocalPhotos = [NSMutableArray arrayWithArray:photos];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"沙盒路径：%@", documentsDirectory);
    
//    NSString *filePath = [documentsDirectory stringByAppendingFormat:@"/image_%ld.jpg", i];
    
    //    _selectedLocalAssets = [NSMutableArray arrayWithArray:assets];
//    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    NSMutableArray *marray= [NSMutableArray array];
//    for  (int i = 0; i< photos.count; i++) {
//        NSString *filePath = [documentsDirectory stringByAppendingFormat:@"/image_%ld.jpg", i];
//        [marray addObject:filePath];
//        NSData *data = UIImagePNGRepresentation(photos[i]);
//        [data writeToFile:filePath atomically:YES];
//    }
    
    for  (int i = 0; i< photos.count; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", i+1]];
        UIImage *image =   photos[i];
        NSString *filePath = [documentsDirectory stringByAppendingFormat:@"/image_%d.jpg", i];
        [marray addObject:filePath];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        [data writeToFile:filePath atomically:YES];
    }
    
    
    if( marray.count == 4 || marray.count == 12) {
        [SVProgressHUD showWithStatus:@"正在合成"];
        NSString *filePath = [FinshUtil finshWithImages:marray];
        [SVProgressHUD dismiss];

        [self saveImageWithImagePath:filePath];
        if(filePath) {
            NSLog(@"成功");
            [self showImageWithFilePath:filePath];
        } else {
            NSLog(@"失败");
        }

    } else {
        [SVProgressHUD showWithStatus:@"图片数量不对"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
    
//    for  (int i = 0; i< _selectedLocalAssets.count; i++) {
//        [self getImagePathFromAsset:_selectedLocalAssets[i] completion:^(NSString *imagePath) {
//            NSLog(@"Image Path: %@", imagePath);
//        }];
//    }
  

    
 }


// 获取图片路径
- (void)getImagePathFromAsset:(PHAsset *)asset completion:(void (^)(NSString *))completion {
    PHImageManager *manager = [PHImageManager defaultManager];
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = YES;
    
    [manager requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        NSURL *imageURL = [info objectForKey:@"PHImageFileURLKey"];
        NSString *imagePath = imageURL.path;
        completion(imagePath);
    }];
}
- (void)finshUtil1 {
    NSLog(@"开始合成");
    NSMutableArray *mArray = [NSMutableArray array];
    NSBundle *bundle = [NSBundle mainBundle];
    [mArray addObject:[bundle pathForResource:@"1" ofType:@"jpg"]];
    [mArray addObject:[bundle pathForResource:@"2" ofType:@"jpg"]];
    [mArray addObject:[bundle pathForResource:@"3" ofType:@"jpg"]];
    [mArray addObject:[bundle pathForResource:@"4" ofType:@"jpg"]];
    
    NSString *filePath = [FinshUtil finshWithImages:mArray];
    [self saveImageWithImagePath:filePath];
    if(filePath) {
        NSLog(@"成功");
        [self showImageWithFilePath:filePath];
    } else {
        NSLog(@"失败");
    }
}

- (void)saveImageWithImagePath:(NSString *)filePath{
    UIImageWriteToSavedPhotosAlbum([UIImage imageWithContentsOfFile:filePath], nil, nil, nil);
}

- (void)addBottom {
    NSString *filePath = [FinshUtil compensationWithFilePath:[[NSBundle mainBundle] pathForResource:@"a" ofType:@"jpg"] logoFilePath:[[NSBundle mainBundle] pathForResource:@"a" ofType:@"jpg"]];
    if(filePath) {
        NSLog(@"补地成功");
        [self showImageWithFilePath:filePath];
    } else {
        NSLog(@"失败");
    }
}

- (void)showImageWithFilePath:(NSString *)filePath {
    if(filePath){
        MyTourWebViewController *controller = [[MyTourWebViewController alloc] init];
        controller.isPresent = YES;
        controller.isAddBack = YES;
        controller.imageFile = filePath;
        [self presentViewController:controller animated:YES completion:nil];
    } else {
        NSLog(@"filePath 为空");
    }
}


@end
